package com.bauer.java.spring.web;

import com.bauer.java.spring.aop.aspectJaop.ProxyBean;
import com.bauer.java.spring.transaction.declarative.DeclarativeTransactionDemo;
import com.bauer.java.spring.transaction.programmtic.ProgrammaticTransactionDemo;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.async.DeferredResult;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @Author ：rui.wei
 * @Date ：Created in 11:21 2018/7/31
 * @Description：
 */
@Controller
public class Hello {

    private String dubbo;


    @Autowired
    private ProxyBean proxyBean;

    @Autowired
    private ProgrammaticTransactionDemo programmaticTransactionDemo;

    @Autowired
    private DeclarativeTransactionDemo declarativeTransactionDemo;

    @RequestMapping("/hello")
    @ResponseBody
    private String hello(HttpServletResponse response) {
        proxyBean.aroundTest("xx");
//        programmaticTransactionDemo.userTransactionManager();
        return "hello";
    }

    @RequestMapping("/async")
    @ResponseBody
    private DeferredResult<String> aync(HttpServletResponse response) {

        DeferredResult<String> deferredResult = new DeferredResult<>();

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                }

                deferredResult.setResult("hello sync");
            }
        }).start();
        return deferredResult;
    }

    @RequestMapping("/index1")
    private void index1(HttpServletResponse response) {
        try {
            String basePath = Hello.class.getResource("/").getPath();
            File file = new File(basePath + "template.pdf");
            IOUtils.toByteArray(new FileInputStream(file));
            response.setContentType("application/com.bauer.java.doc.pdf");
            response.addHeader("Content-Disposition", "attachment; filename=" + "asdfasdf.com.bauer.java.doc.pdf");
            response.getOutputStream().write(IOUtils.toByteArray(new FileInputStream(file)));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
